package com.example.sharesinfo.fragment.index;


import android.os.Bundle;

import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;

import com.example.sharesinfo.MainActivity;
import com.example.sharesinfo.R;
import com.example.sharesinfo.adapter.CommonAdapter;
import com.example.sharesinfo.adapter.CommonViewHolder;
import com.example.sharesinfo.base.BaseFragment;
import com.example.sharesinfo.bean.FlashNewsBean;
import com.example.sharesinfo.bean.NewsBean;
import com.example.sharesinfo.model.FlashNewsModel;
import com.example.sharesinfo.model.RecommendModel;
import com.example.sharesinfo.utils.CommonUtils;
import com.example.sharesinfo.utils.LogUtils;
import com.example.sharesinfo.utils.OkHttpUtils;
import com.google.gson.Gson;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * A simple {@link Fragment} subclass.
 */
public class NewsFlashFragment extends BaseFragment {
    private boolean isPrepared = false;     //标志位，标志已经初始化完成
    private static final String LogTag = "NewsFlashFragment:";
    private LinearLayout ll_dialog;
    private View item_empty_view;
    private RecyclerView mvFlashNewsView;
    private SmartRefreshLayout mSrl;
    private int page = 1;
    private CommonAdapter<FlashNewsModel> mFlashNewsAdapter;
    private List<FlashNewsModel> mList = new ArrayList<>();
    private static final int MAXPAGE = 10000;
    //用来分页的数组
    private List<FlashNewsModel> mPageList = new ArrayList<>();
    //传递新闻数据
    private static final int QUERYNEWSSUCCESS = 1001;
    private static final int QUERYNEWSFAILED = 1002;
    private final Handler mHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            switch (msg.what) {
                case QUERYNEWSSUCCESS:
                    LogUtils.i(LogTag + "查询成功");
//                    if (mList.size() > 0) {
//                        mList.clear();
//                    }
                    ll_dialog.setVisibility(View.GONE);
                    item_empty_view.setVisibility(View.GONE);
                    mvFlashNewsView.setVisibility(View.VISIBLE);
                    FlashNewsBean result = (FlashNewsBean) msg.obj;
                    mList.addAll(result.getData());
                    getData(getPageList(mList));
                    mFlashNewsAdapter.notifyDataSetChanged();
                    break;
                case QUERYNEWSFAILED:
                    item_empty_view.setVisibility(View.GONE);
                    mvFlashNewsView.setVisibility(View.VISIBLE);
                    page = MAXPAGE;
                    break;
                case 404:
                    item_empty_view.setVisibility(View.VISIBLE);
                    mvFlashNewsView.setVisibility(View.GONE);
                    break;
            }
            return false;
        }
    });

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_news_flash, null);
        initView(view);
        return view;
    }

    private void initView(View view) {
        ll_dialog = view.findViewById(R.id.ll_dialog);
        ll_dialog.setVisibility(View.VISIBLE);
        item_empty_view = view.findViewById(R.id.item_empty_view);
        mSrl = view.findViewById(R.id.refreshLayout);
        mvFlashNewsView = view.findViewById(R.id.mFlashNewsView);
        //下拉刷新
        mSrl.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshLayout) {

                //下拉刷新
                if (mPageList.size() > 0) {
                    mPageList.clear();
                }
                refreshLayout.finishRefresh(1000);
                LogUtils.i(LogTag + "下拉刷新");
                page = 1;
                queryKuaiXun(page);
            }
        });
        //加载更多
        mSrl.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(RefreshLayout refreshLayout) {
                LogUtils.i(LogTag + "加载更多" + page);
                if (page == MAXPAGE) {
                    refreshLayout.finishLoadMoreWithNoMoreData();
                } else {
                    page++;
                    queryKuaiXun(page);
                    refreshLayout.finishLoadMore(1000);
                }

            }
        });
        mvFlashNewsView.setLayoutManager(new LinearLayoutManager(getActivity()));
        mvFlashNewsView.addItemDecoration(new DividerItemDecoration(getActivity(),
                DividerItemDecoration.VERTICAL));
    }

    /**
     * 加载更多，将新获取的数据加入list中
     */
    private List<FlashNewsModel> getPageList(List<FlashNewsModel> pageList) {
        mPageList.addAll(pageList);
        return mPageList;
    }

    /**
     * 填充数据
     */
    private void getData(final List<FlashNewsModel> list) {
        LogUtils.i(LogTag + list.toString());
        if (list == null || list.size() == 0) {
            return;
        }
        if (mFlashNewsAdapter == null || page == 1) {
            LogUtils.i(LogTag + "page=1");
            mFlashNewsAdapter = new CommonAdapter<>(mList, new CommonAdapter.OnBindDataListener<FlashNewsModel>() {
                @Override
                public void onBindViewHolder(FlashNewsModel model, CommonViewHolder viewHolder, int type, int position) {
                    viewHolder.setText(R.id.tv_time, model.getIssueTime());
                    viewHolder.setText(R.id.tv_title, model.getTitle());
                    viewHolder.setText(R.id.tv_content, model.getContent());
                    viewHolder.setText(R.id.tv_source, "来源:" + model.getSource());
                }

                @Override
                public int getLayoutId(int type) {
                    return R.layout.news_flash_item;
                }
            });
            mvFlashNewsView.setAdapter(mFlashNewsAdapter);
        } else {
            mFlashNewsAdapter.notifyDataSetChanged();
        }
    }

    /**
     * 快讯列表（page:为页数）
     */
    private void queryKuaiXun(int page) {
        String url = "http://119.23.221.142/api/information/GetKuaiXunList?page=" + page;
        LogUtils.i(LogTag + url);
        OkHttpUtils.getInstance().Get(url, new OkHttpUtils.okHttpListener() {
            Message mess = mHandler.obtainMessage();

            @Override
            public void OnSuccess(String s, int code) throws JSONException {
                JSONObject object = new JSONObject(s);
                if (object.getString("code").equals("200")) {
                    FlashNewsBean bean = new Gson().fromJson(s, FlashNewsBean.class);
                    mess.what = QUERYNEWSSUCCESS;
                    mess.obj = bean;
                    mHandler.sendMessage(mess);
                } else {
                    mess.what = QUERYNEWSFAILED;
                    mess.obj = object.getString("message");
                    mHandler.sendMessage(mess);
                }
            }

            @Override
            public void OnFailed(String s) {
                mess.what = 404;
                mess.obj = s;
                mHandler.sendMessage(mess);
            }
        });
    }

    @Override
    public void onResume() {
        if (!isPrepared) {
            queryKuaiXun(1);
            isPrepared = true;
        }
        super.onResume();

    }
}
